<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="import_add content">
      <e-heading>学员报名</e-heading>
       <el-form :model="form" ref="form" label-width="100px">
         <el-row>
          <el-col :span="10" style="margin-bottom:0;">
            <el-form-item label="课程名称：" prop="className" :rules="{ required: true, message: '请选择课程名称'}">
              <el-select placeholder="请选择课程名称" style="width:90%;"
                clearable
                v-model="form.className"
                value-key="id"
                @visible-change="handleSelectVisible"
                @change="handleSelectClass">
                <el-option v-for="item in train_selectclass_list" :key="item.id" :label="item.courseName" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="24">
            <h2 class="class_title">课程名称： {{$route.query.name}}</h2>
          </el-col>
        </el-row> -->
        <el-row v-if="form.className && !isCkType">
          <el-col :span="10" style="margin-bottom:0;">
            <el-form-item label="校 区：" prop="campus" :rules="{ required: true, message: '请选择校区'}">
              <el-select v-model="form.campus" placeholder="请选择校区" clearable style="width:90%;">
                <el-option v-for="item in train_scholl_type_list" :key="item.key" :label="item.value" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10" style="margin-bottom:0;">
            <el-form-item label="班 别：" prop="type" :rules="{ required: true, message: '请选择班别'}">
              <el-select v-model="form.type" placeholder="请选择班别" clearable style="width:95%;">
                <el-option v-for="item in train_class_type_list" :key="item.key" :label="item.value" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-scrollbar class="import_table" wrap-class="student_scroll">
        <el-table ref="multipleTable" :data="list" empty-text="暂无学员" stripe tooltip-effect="dark" style="width: 100%">
          <el-table-column label="序号" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.$index + 1}}
            </template>
          </el-table-column>
          <el-table-column prop="name" align="left" label="姓名" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="parentMobile" align="center" label="手机号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-button type="link" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="link" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <p style="text-align:center;margin-top:20px;"><el-button @click="handleSignStudents()" type="link" icon="plus">添加报名学员<span style="font-size:12px;color:#999;">（一次最多可添加50人）</span></el-button></p>
      </el-scrollbar>
      <div class="button-box">
        <el-button v-if="list.length > 0" @click="handleCancel">取 消</el-button>
        <el-button type="primary" v-if="list.length > 0" :loading="loading" @click="handleAddStudents">报 名</el-button>
      </div>
      <!--添加学员-->
      <el-dialog
        title="填写学员信息"
        v-if="dialogVisible"
        :visible.sync="dialogVisible" @close="handleColse">
        <student-info :isAdd="isAdd" :formList="formList" :studentInfo="studentInfo" :type="isCkType" :isSet="true" v-if="isClose" v-model="isClose" @success="handleSuccess" @setInfo="handleSetInfo"></student-info>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import trainApi from 'api/train'
import StudentInfo from '../student/components/StudentInfo'
export default {
  components: {
    StudentInfo
  },
  computed: {
    ...mapGetters({
      train_scholl_type_list: 'train_scholl_type_list',
      train_class_type_list: 'train_class_type_list',
      train_selectclass_list: 'train_selectclass_list'
    })
  },
  created () {
    window.tyler = this
    this.$store.dispatch('train_selectclass_list')
  },
  data () {
    return {
      classData: '',
      loading: false,
      isAdd: true,
      isEdit: false,
      isClose: true,
      dialogVisible: false,
      selectStudents: [],
      list: [],
      studentInfo: {},
      formList: [],
      isCkType: false, // 是否是次课
      isShowTips: false, // 是否弹窗确认切换课程 新增新的学员时 改为true 报名后 改为 false
      form: {
        className: '',
        type: '',
        campus: ''
      }
    }
  },
  methods: {
    handleSelectClass (classObj) {
      /**
       * $backClassData 存储上一次数据 做判断，防止取消后的改变触发改变流程
       * classObj 不管是否是清空值 都需要自行这一步操作
       */
      this.$backClassData = this.$backClassData || {}
      if (classObj.id === this.$backClassData.id) return false // id相同 中断流程
      if (this.isShowTips && this.list.length) { // 是否需要弹窗提示
        // let h = this.$createElement
        this.$msgbox({
          title: '温馨提示',
          message: '改变课程，已输入的学员将不会保存哦！',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.initClassData(classObj) // 确认改变处理
        }).catch(() => {
          this.form.className = this.$backClassData // 取消改变 回复改变的值
        })
        return false
      }
      this.initClassData(classObj) // 默认操作
    },
    initClassData (classObj) {
      // 这里也是无视classObj的值
      this.$backClassData = classObj || {}
      let { id, properties } = classObj
      this.isCkType = Boolean(properties - 0 === 2)
      this.list = [] // 清空学员列表
      // 如果 classObj的id没值  则不执行
      if (!classObj) return false
      trainApi.studentGetForm({courseId: id}).then(({data}) => {
        this.formList = data.fields
      })
      // 所有课程都需要请求更新
      // if (!this.isCkType) {
      this.$store.dispatch('train_scholl_type_list', {courseId: id})
      this.$store.dispatch('train_class_type_list', {courseId: id})
      // }
    },
    handleSelectVisible (visible) {
      // dsadsa
    },
    handleSignStudents () { // 添加学员
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.list.length === 50) {
            this.$message.error('一次最多可添加50人哦')
          } else {
            this.isAdd = true
            this.dialogVisible = true
            this.isClose = true
            this.isEdit = false
            this.studentInfo = {
              courseId: this.form.className.id
            }
          }
        }
      })
    },
    handleSetInfo (val) { // 自动匹配已存在学员
      this.studentInfo = val
    },
    handleColse () {
      this.studentInfo = {}
      this.isClose = false
    },
    handleEdit (index, row) {
      this.dialogVisible = true
      this.isClose = true
      this.isEdit = true
      let scope = this
      setTimeout(function () {
        scope.studentInfo = row
        scope.editIndex = index
      }, 300)
    },
    handleDelete (index, row) {
      let h = this.$createElement
      this.$msgbox({
        title: '温馨提示',
        message: h('div', null, [
          h('div', {style: 'width: 130px; word-break: break-all; padding-bottom: 10px;'}, '删除后不可恢复'),
          h('div', {style: 'width: 240px;'}, '确认删除该学员吗？')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.list.filter((item, n) => {
          if (n === index) {
            this.list.splice(n, 1)
          }
          return this.list
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // console.log(err)
      })
    },
    handleSuccess (value) {
      // 更改提示状态 新增学员成功 提示状态改为true
      this.isShowTips = true
      // 其他业务处理
      let isExist = false // 手机号+学员姓名已存在于列表
      let isIdNo = false // 证件号码已存在于列表
      let errMsg = '您刚才添加过该学员啦！'
      let idNoMsg = '您刚才添加过该证件号码啦！'
      if (this.isEdit) {
        for (let i = 0; i < this.list.length; i++) {
          if (i !== this.editIndex) {
            if (this.list[i].parentMobile === value.parentMobile && this.list[i].name === value.name) {
              isExist = true
            }
          }
        }
        if (isExist) {
          this.$message.error(errMsg)
          this.dialogVisible = false
          return
        }
        this.list.splice(this.editIndex, 1, value)
        this.dialogVisible = false
      } else {
        for (let j = 0; j < this.list.length; j++) {
          if (this.list[j].parentMobile === value.parentMobile && this.list[j].name === value.name) {
            isExist = true
          } else if (this.list[j].idNo && this.list[j].idNo === value.idNo) {
            isIdNo = true
          }
        }
        if (isExist) {
          this.$message.error(errMsg)
          this.dialogVisible = false
          return
        } else if (isIdNo) {
          this.$message.error(idNoMsg)
          this.dialogVisible = false
          return
        }
        this.list.push(value)
        this.dialogVisible = false
      }
    },
    handleCancel () {
      let h = this.$createElement
      this.$msgbox({
        title: '温馨提示',
        message: h('div', null, [
          h('div', {style: 'width: 130px; word-break: break-all; padding-bottom: 10px;'}, '要离开此页面吗？'),
          h('div', {style: 'width: 240px;'}, '系统不会保存您所添加的信息哦！')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        history.back()
      }).catch(() => {})
    },
    handleAddStudents () { // 提交报名数据
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.isCkType) {
            this.list.forEach((item) => {
              item.courseId = this.form.className.id
              item.schoolId = this.form.campus.key
              item.classesId = this.form.type.key
            })
          }
          trainApi.classBatcjSign(JSON.stringify(this.list), {context: this, successMsg: '学员报名成功'}).then((res) => {
            // 更改提示状态 报名成功 提示状态改为false
            this.isShowTips = false
            this.list = []
            this.form.className = ''
            this.form.campus = ''
            this.form.type = ''
            this.$refs.form.resetFields()
            // this.$router.push({path: '/training/curriculum'})
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
.import_add{
  .el-dialog--small {
    width: 600px;
  }
  .el-dialog__body {
    padding-bottom: 90px;
  }
  .vacade-scroll{
    max-height: 490px;
    overflow-y: scroll;
  }
  .import-stutips {
    .el-scrollbar .el-scrollbar__bar{
      opacity: 1;
      transition: opacity 340ms ease-out
    }
  }
  .form-search{
    border-bottom:1px solid #efefef;
  }
  .class_title{
    font-size:16px;
  }
  .el-col{
    margin-bottom:22px;
  }
  .import-stutips{
    .el-col{
      margin-bottom:0;
    }
    .el-form-item__content > .el-input, .el-form-item__content > .el-cascader, .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .class_list{
    color:#00bb90;
    font-weight:bold;
    line-height:1.3;
    .el-col{
      padding:0 5px 0 0;
    }
  }
  .detail-top{
    line-height: 2;
  }
  .import_table{
    margin:10px 0 20px 0;
    .el-checkbox{
      margin:0;
    }
    .el-table .cell{
      font-size:12px;
      padding:0 10px;
    }
  }
}
</style>
